﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iLangl.Transport;
using iLangl.Security;
using iLangl.Plugin;
using iLangl.Customer.DNN.Configuration;
using iLangl.Customer.DAL;
using DotNetNuke.Common;
using iLangl.Transport.Communication;

namespace iLangl.Customer.DNN
{
	public class DNNConfigurationManager : IConfigurationManager
	{
		private DNNConfigurationManager()
		{
			initializeCustomerFacade();
			PushServiceManager.Instance.Initialize();
			PushServiceManager.Instance.Open();
			
		}

		#region Singelton Pattern
		private static DNNConfigurationManager instance;
		private static object mutex = new object();
		/// <summary>
		/// The instance of the DNNConfigurationManager.
		/// </summary>
		public static DNNConfigurationManager Instance
		{
			get
			{
				if (instance == null)
				{
					lock (mutex)
					{
						if (instance == null)
						{
							instance = new DNNConfigurationManager();
						}
					}
				}
				return instance;
			}
		}
		#endregion

		//TODO: Remove hardcoded url
		protected ITransport transport = new WCFConsumer("http://localhost:8080/ilangl/transport");

		//Customer Facade
		CustomerFacade customerFacade = null;
		public CustomerFacade CustomerFacade
		{
			get
			{
				if (customerFacade == null)
				{

					initializeCustomerFacade();
				}

				return customerFacade;
			}
		}

		private void initializeCustomerFacade()
		{
			//Customer Business Model Test Setup
			customerFacade = new CustomerFacade();
			customerFacade.CommunicationManager.Transport = transport;

			Facade.Instance.Initialize(customerFacade);
		}

	
		#region IConfigurationManager Members

		public IPluginConfiguration GetPluginConfiguration()
		{
			return GetPluginConfiguration(SiteId);
		}

		const Int32 pluginConfigurationType = 1;

		public void SavePluginConfiguration(IPluginConfiguration pluginConfiguration)
		{
			if (String.IsNullOrEmpty(pluginConfiguration.SiteId))
				throw new ArgumentNullException("pluginConfiguration.SiteId");

			String pluginContent = SerializationHelper.SerializeOject(pluginConfiguration);
			DALFacade.Instance.ConfigurationDAL.Save(pluginConfigurationType, pluginConfiguration.SiteId, pluginContent);
		}


		public IPluginConfiguration GetPluginConfiguration(string siteId)
		{
			string content = DALFacade.Instance.ConfigurationDAL.ReadSettings(pluginConfigurationType, siteId);

			if (String.IsNullOrEmpty(content))
			{
				IPluginConfiguration result  = ConfigurationFactory.Instance.CreatePluginConfiguration();
				return result;
			}

			return (IPluginConfiguration)SerializationHelper.DeserializeObject(content, ConfigurationFactory.Instance.CreatePluginConfiguration().GetType());
		}

		public String SiteId
		{
			get
			{
				return Globals.GetPortalSettings().PortalId.ToString();
			}
		}

		#endregion
	}
}